package com.vnp.vchat;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.vchat.UIControls.SwipeDismissListViewTouchListener;
import com.vnp.vchat.Util.Common;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.adapter.ChatAdapter;
import com.vnp.vchat.adapter.TinnhanAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.bean.ObjMsgChat;
import com.vnp.vchat.bean.ObjTinnhan;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class TinNhanActivity extends Activity implements OnTouchListener{

	TextView title;
	ImageButton btnSettings;
	ArrayList<ObjKhachhang> objKhachhangs = new ArrayList<ObjKhachhang>();
	TinnhanAdapter adapter;
	ListView listTinnhan;
	PreferenceHelper preferenceHelper;
	
	Handler mHandler = new Handler();
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			getDanhsach(mPage);
		}
	};
	
	ProgressBar progressBar;
	
	LinearLayout llNomsg;
	TextView txtNoMsg;
	Button btnSoantin;
	
	//load more hischat
	private int preLast;
	boolean isLoading = false;
	boolean isCanloadMore = false;
	int mPage = 1;
	
	MySQLiteHelper db;
	private BroadcastReceiver mReceiver;
	ViewGroup actionbar;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tin_nhan);
		
		db = new MySQLiteHelper(this);
		
		
		preferenceHelper = new PreferenceHelper(TinNhanActivity.this);
		
		actionbar = (ViewGroup) findViewById(R.id.actionbar);
		title = (TextView) findViewById(R.id.title);
		btnSettings = (ImageButton) findViewById(R.id.btn_settings);
		progressBar = (ProgressBar) findViewById(R.id.progress_bar);
		
		llNomsg = (LinearLayout) findViewById(R.id.ll_nomsg);
		txtNoMsg = (TextView) findViewById(R.id.txt_nomsg);
		btnSoantin = (Button) findViewById(R.id.btn_soantin);
		
		btnSettings.setVisibility(View.GONE);
		progressBar.setVisibility(View.VISIBLE);
		
		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 300);
		
//		setDataDemo();
		
		listTinnhan = (ListView) findViewById(R.id.list_tinnhan);
		
		
		objKhachhangs = db.getAllHisChat();
		
		Log.i("vChat", "List hischat to DB: "+objKhachhangs.size());
		
		adapter = new TinnhanAdapter(TinNhanActivity.this, objKhachhangs);
		listTinnhan.setAdapter(adapter);
		
		setData();
		setFont();
		
		listTinnhan.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				MainActivity.onGoto = true;
				Intent c = new Intent(TinNhanActivity.this,ChatActivity.class);
				c.putExtra("khachhang", objKhachhangs.get(position));
				startActivity(c);
				TinNhanActivity.this.overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
			}
		});
		
		listTinnhan.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastItem = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount) {
					  if (preLast != lastItem) { 
						  int last_pos = listTinnhan.getLastVisiblePosition(); 
						  if (last_pos >=objKhachhangs.size() - 1 && !isLoading && isCanloadMore){
							 btnSettings.setVisibility(View.GONE);
							 progressBar.setVisibility(View.VISIBLE);
							 getDanhsach(++mPage);
						  } 
						  preLast = lastItem; 
					  }
					
				}
			}
		});
		
		/*// set swipe nguyen lieu
		SwipeDismissListViewTouchListener touchListener =
	        new SwipeDismissListViewTouchListener(
	                listTinnhan,
	                new SwipeDismissListViewTouchListener.OnDismissCallback() {
	                    @Override
	                    public void onDismiss(ListView listView, int[] reverseSortedPositions) {
	                        for (int position : reverseSortedPositions) {
	                            adapter.remove(adapter.getItem(position));
	                        }
	                        adapter.notifyDataSetChanged();
	                    }
	                });
		
		listTinnhan.setOnTouchListener(touchListener);
		listTinnhan.setOnScrollListener(touchListener.makeScrollListener());*/
		
		reciveBroadCast();
		init();
	}
	
	private void init() {
		btnSettings.setOnTouchListener(this);
		actionbar.setOnTouchListener(this);
		title.setOnTouchListener(this);
	};
	
	ArrayList<ObjKhachhang> setDataDemo(){
		objKhachhangs.add(new ObjTinnhan("","Thientvse", "Xin chào bạn...", "13/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/IJbtXg", "D.Beckham","Hello Vietnam...", "14/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/xbqfJI", "C.Ronaldo", "I'm from Portugal...", "15/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/fg1W0h", "L.Messi", "Ha ha ha ha...", "16/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/UuhcT7", "W.Rooney", "Hi Vietnam...", "17/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/Uflmzm", "Kaka", "Bye!See you again...", "18/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/qwYv7e", "Di Maria", "Worldcup 2014", "19/06/2014"));
		objKhachhangs.add(new ObjTinnhan("http://goo.gl/ikcm5G", "R.Persie", "Xin chào bạn...", "20/06/2014"));
		
		return objKhachhangs;
	}
	
	private void setFont() {
		
//		title.setTypeface(Utils.getTypefaceBlack(TinNhanActivity.this), Typeface.BOLD);
		txtNoMsg.setTypeface(Utils.getTypefaceRegular(TinNhanActivity.this), Typeface.BOLD);
		btnSoantin.setTypeface(Utils.getTypefaceRegular(TinNhanActivity.this), Typeface.BOLD);
	}
	private void setData() {
		title.setText(R.string.tinnhan);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_settings:
			if (event.getAction() == MotionEvent.ACTION_UP){
				
			}
			break;
		case R.id.actionbar:
			if(event.getAction() == MotionEvent.ACTION_UP){
				scrollToTop();
			}
			
		case R.id.title:
			if(event.getAction() == MotionEvent.ACTION_UP){
				Log.i("vChat", "Click vào title------------");
				scrollToTop();
			}
		default:
			break;
		}
		return false;
	}
	
	void scrollToTop(){
		listTinnhan.smoothScrollToPosition(0);
	}
	
	public void getDanhsach(int page){
		isLoading = true;
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				btnSettings.setVisibility(View.GONE);
				progressBar.setVisibility(View.GONE);
				isLoading = false;
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					btnSettings.setVisibility(View.GONE);
					progressBar.setVisibility(View.GONE);
					isLoading = false;
					int status = re.getInt("status");
					if (status == 1){
						
						
						JSONArray his = re.getJSONArray("history");
						
						Log.i("vChat", "His: "+his);
//						db.deleteHisChat();
						for (int i = 0; i < his.length(); i++) {
							
							
							
							JSONObject hisMsg = his.getJSONObject(i);
							String name ;
							
							if (his.length() < 19){
								isCanloadMore = false;
							} else {
								isCanloadMore = true;
							}
							
							if (!hisMsg.getString("use_name").equals("") && !(hisMsg.getString("use_name").equals(null))){
								name = hisMsg.getString("use_name");
							} else {
								name = hisMsg.getString("use_loginname");
							}
						
							String urlAvatar = hisMsg.getString("to_image");
							
							Log.i("vChat", "URL avatar: "+urlAvatar);
							
							String lastMsg, time;
							
							if (hisMsg.getJSONArray("last_msg").length() == 0){
								Log.i("vChat", "Ko co gia tri last message");
								lastMsg = "";
								time = "";
							} else {
								lastMsg = hisMsg.getJSONArray("last_msg").getJSONObject(0).getString("cha_message");
								time = hisMsg.getJSONArray("last_msg").getJSONObject(0).getString("cha_time");
							}
							
							
							int online = hisMsg.getInt("online");
							int idKh = hisMsg.getInt("uss_sso_id");
							int isUserVg = hisMsg.getInt("is_uservg");
							
							
							String pro_name = null, pro_url = null;
							
							// check danh sach da xem
							Object obj = hisMsg.get("pro");
							if (obj instanceof JSONObject){
								JSONObject proObj = (JSONObject) obj;
								
								pro_name = proObj.getString("pro_name");
								pro_url = proObj.getString("pro_link");
								
							} else  {
								pro_name = "";
								pro_url = "";
								Log.i("vChat", "Ko co ds da xem -----------");
							}
							
							int statusMsg = db.getStatusMsg(String.valueOf(idKh));
							
							if (idKh == Integer.valueOf(preferenceHelper.getUserId())){
								
							} else {
								ObjKhachhang objKhachhang = new ObjKhachhang();
								objKhachhang.setName(name);
								objKhachhang.setUrlAvatar(urlAvatar);
								objKhachhang.setLastMessage(lastMsg);
								objKhachhang.setTimeLastMessage(time);
								objKhachhang.setOnline(online);
								objKhachhang.setId(String.valueOf(idKh));
								objKhachhang.setIsUserVg(isUserVg);
								objKhachhang.setUrlDangxem(pro_url);
								objKhachhang.setDsDaxem(pro_name);
								objKhachhang.setIsRead(statusMsg);
//								db.insertHisChat(objKhachhang);
								db.updateHischat(objKhachhang);
							}
						}
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								getDataToDB();
							}
						});
						if (objKhachhangs.size()>0){
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									adapter.notifyDataSetChanged();
									listTinnhan.setAdapter(adapter);
								}
							});
							
							llNomsg.setVisibility(View.GONE);
							listTinnhan.setVisibility(View.VISIBLE);
						} else {
							llNomsg.setVisibility(View.VISIBLE);
							listTinnhan.setVisibility(View.GONE);
							
						}
						
					} else if (status == 0) {
						
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.getDanhsachChat(preferenceHelper.getUserId(), preferenceHelper.getHash(), page, 1);
		
	}
	
	
	void getDataToDB(){
		objKhachhangs = db.getAllHisChat();
		adapter = new TinnhanAdapter(TinNhanActivity.this, objKhachhangs);
		listTinnhan.setAdapter(adapter);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		KeyboardHelper.hideSoftKeyboard(TinNhanActivity.this);
		getDataToDB();
//		objKhachhangs.clear();
		mPage = 1;
		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 200);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacksAndMessages(null);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacksAndMessages(null);
	}
	
	private void reciveBroadCast(){
		IntentFilter intentFilter = new IntentFilter();
		
		
		 intentFilter.addAction(Common.IS_READ);
		 intentFilter.addAction(Common.ADD);
		 intentFilter.addAction(Common.IS_RELOAD);
		    
		    mReceiver = new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, final Intent intent) {
					String action = intent.getAction();
					if (action.equals(Common.IS_READ)){
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								objKhachhangs = db.getAllHisChat();
								adapter = new TinnhanAdapter(TinNhanActivity.this, objKhachhangs);
								listTinnhan.setAdapter(adapter);
								/*mHandler.removeCallbacks(r);
								mHandler.postDelayed(r, 200);*/
//								adapter.notifyDataSetChanged();
							}
						});
						Log.i("vChat", "Nhan duoc broadcast update trang thai");
					} else if (action.equals(Common.ADD)) {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								objKhachhangs = db.getAllHisChat();
								adapter = new TinnhanAdapter(TinNhanActivity.this, objKhachhangs);
								listTinnhan.setAdapter(adapter);
							}
						});
					} else if (action.equals(Common.IS_RELOAD)) {
						mHandler.removeCallbacks(r);
						mHandler.postDelayed(r, 300);
					}
				}
			};
			
			// register
			this.registerReceiver(mReceiver, intentFilter);
	}
	
	
	
	
	
	
}
